let testClazz = '';

window.addEventListener('DOMContentLoaded', () => {
  app.initPage();
  testClazz = localStorage.getItem('testClazz');
});

function loadPage() {
  create();
  loadClazzTypeList();
}

function create() {
  layui.use(['element', 'form', 'layer'], () => {
    let form = layui.form,
      layer = layui.layer;
    form.on('submit(create)', obj => {
      let field = obj.field,
        layuiCard = $('.layui-card');
      if (layuiCard.length === 0) {
        layer.msg('请添加题目之后再创建试题');
      } else {
        let everyTest = {},
          testBank = [],
          sumScale = 0,
          singleScale = parseFloat(field.singleScale),
          multiScale = parseFloat(field.multiScale);
        for (let i = 0; i < layuiCard.length; i++) {
          everyTest.testTitle = field.testTitle;
          everyTest.subject = layuiCard.eq(i).find('.subjectId').val();
          everyTest.testClazz = field.subjectClazz;
          everyTest.testTime = field.restrict;
          everyTest.testNo = i + 1;
          everyTest.createdBy = $('#name').text();
          let subjectType = layuiCard.eq(i).find('.ques-type').text();
          switch (subjectType) {
            case '1':
              everyTest.singleScale = singleScale;
              sumScale += singleScale;
              break;
            case '2':
              everyTest.singleScale = multiScale;
              sumScale += multiScale;
              break;
            case '3':
              let openScale = parseFloat(layuiCard.eq(i).find('.openScale').val());
              everyTest.singleScale = openScale;
              sumScale += openScale;
              break;
          }
          everyTest.sumScale = sumScale;
        }
        testBank.push(everyTest);
        testBank = JSON.stringify(testBank);
        $.post(`${app.urlLocation.addRandomTest}`, {testPaperString: testBank}, res => {
          if (res === 200) {
            layer.msg('试卷创建成功，正在进行跳转');
            setTimeout(() => {
              window.location.href = '/teacher-action/test';
            }, 1000);
          } else {
            layer.msg('试卷创建失败，请重试或联系系统管理员');
          }
        })
      }
    })
  })
}

function loadClazzTypeList() {
  layui.use(['element', 'layer'], () => {
    $.ajax({
      url: app.urlLocation.queryAllCt,
      type: 'get',
      success: function (data) {
        let html = '';
        $.each(data, function (i, v) {
          html += `<option value="${v.id}">${v.classType}</option>`;
        });
        $('select[name=subjectClazz]').html(html);
        app.resetForm();
      },
      error: function () {
        alertInfo('网站服务出现异常，请联系管理员!');
      }
    });
  });
  app.resetForm();
}

function returnToTest() {
  layui.use('layer', () => {
    let layer = layui.layer;
    layer.confirm('现在返回将丢失当前页码所有试题内容，是否跳转?', {
      btn: ['跳转', '不跳转']
    }, () => {
      window.location.href = '/teacher-action/test';
    })
  })
}

function addQuestion() {
  loadAllClazz();
  showLayout($('.layout'));
}

function loadAllClazz() {
  $.get(`${app.urlLocation.queryAllClazz}`, {
    page: app.pageHelper.global_page,
    limit: app.pageHelper.global_limit,
    subjectClazz: testClazz
  }, res => {
    if (res.data.length === 0 && app.pageHelper.global_page > 1) {
      app.pageHelper.global_page--;
      loadAllClazz();
    } else {
      loadClazzTable(res);
      loadClazzPage(res);
    }
  })
}

function loadClazzTable(clazz) {
  layui.use('table', () => {
    let table = layui.table;
    table.render({
      elem: '#testClazz',
      data: clazz.data,
      limit: app.pageHelper.global_limit,
      cols: [
        [
          {field: 'subjectTitle', title: '题目'},
          {
            field: 'subjectType', title: '题目类型', templet: d => {
              switch (d.subjectType) {
                case 1:
                  return '单选';
                case 2:
                  return '多选';
                case 3:
                  return '开放题';
              }
            }
          },
          {field: 'subjectContent', title: '选项'},
          {field: 'subjectAnswer', title: '参考答案'},
          {
            field: 'createdTime', title: '创建时间', templet: d => {
              return app.formatDate(new Date(d.createdTime));
            }
          }
        ]
      ]
    });
    table.on('row(tc)', obj => {
      let data = obj.data;
      let index = $('.layui-card').length;
      $('.add-question').before(writeCard(data, index));
    });
  })
}

function loadClazzPage(clazz) {
  layui.use('laypage', () => {
    layui.laypage.render({
      elem: 'tc-page',
      curr: app.pageHelper.global_page,
      count: clazz.count,
      limit: app.pageHelper.global_limit,
      jump: function (obj, first) {
        if (!first) {
          app.pageHelper.global_page = obj.curr;
          app.pageHelper.global_limit = obj.limit;
          loadAllClazz();
        }
      }
    });
  })
}

function writeCard(data, index) {
  let subjectType = data.subjectType,
    headerProHtml = '',
    subjectContent = data.subjectContent,
    subjectAnswer = data.subjectAnswer,
    subjectId = data.subjectId;
  switch (subjectType) {
    case 1:
      headerProHtml += layuiCardHtml(data, index + 1);
      let subjectOption = subjectContent.split('|');
      $.each(subjectOption, (i, v) => {
        if (parseInt(subjectAnswer) === i + 1)
          headerProHtml += returnSingleOption(subjectId, v, true);
        else
          headerProHtml += returnSingleOption(subjectId, v, false);
      });
      headerProHtml += '</div></div>';
      break;
    case 2:
      headerProHtml += layuiCardHtml(data,  index + 1);
      let multiSubjectOption = subjectContent.split('|'),
        multiSubjectAnswer = subjectAnswer.split('|');
      $.each(multiSubjectOption, (i, v) => {
        if (parseInt(multiSubjectAnswer[i]) === i + 1)
          headerProHtml += returnMultiOption(subjectId, v, true);
        else
          headerProHtml += returnMultiOption(subjectId, v, false);
      });
      headerProHtml += '</div></div>';
      break;
    case 3:
      headerProHtml += returnOpenHeader(data.subjectId, data.subjectTitle,  index + 1);
      headerProHtml += returnOpenOption(data.subjectAnswer);
      break;
  }
  $('.add-question').before(headerProHtml);
  hideLayout($('.layout'));
  app.resetForm();
}

function layuiCardHtml(data, length) {
  return `<div class="layui-card"><input type="text" class="layui-hide subjectId" value="${data.subjectId}` +
    `"><div class="layui-card-header">` +
    `<label class="layui-form-label">第<span class="question-no">${length}` +
    `</span>题</label><div class="layui-input-block">`+
    `<input type="text" name="question" value="${data.subjectTitle}" class="layui-input layui-input-radius"` +
    ` autocomplete="off" lay-verify="required" readonly="readonly">` +
    `<i class="layui-icon layui-icon-delete" onclick="delQuestion($(this));"></i></div>` +
    `<span class="ques-type">${data.subjectType}</span></div><div class="layui-card-body">`;
}

function returnSingleOption(id, data, flag) {
  let isChecked = flag ? `<i class="layui-icon layui-icon-ok"></i>` : ``;
  return `<div class="layui-input-block">` +
    `<input type="text" name="option${id}" readonly="readonly"` +
    ` class="layui-input layui-input-radius" value="${data}"` +
    ` title="" lay-verify="required" autocomplete="off">${isChecked}</div>`;
}

function returnMultiOption(id, data, flag) {
  let isChecked = flag ? '<i class="layui-icon layui-icon-ok"></i>' : '';
  return `<div class="layui-input-block">` +
    `<input type="text" name="option${id}" readonly="readonly" value="${data}"` +
    ` class="layui-input layui-input-radius"` +
    ` title="" lay-verify="required" autocomplete="off">${isChecked}</div>`
}

function returnOpenHeader(subjectId, subjectTitle, index) {
  return '<div class="layui-card"><input type="text" class="layui-hide" value="' + subjectId +
    '"><div class="layui-card-header">' +
    '<label class="layui-form-label">第<span class="question-no">' + index + '</span>题</label>' +
    '<div class="layui-input-block">' +
    '<input type="text" name="question" readonly="readonly" value="' + subjectTitle + '"' +
    ' class="layui-input layui-input-radius open"' +
    ' title="" lay-verify="required" autocomplete="off">' +
    '<input type="text" name="openScale" placeholder="请输入题目分值"' +
    ' class="layui-input layui-input-radius open"' +
    ' title="" lay-verify="required" autocomplete="off">' +
    '<i class="layui-icon layui-icon-delete" onclick="delQuestion($(this));"></i>' +
    '</div><span class="ques-type">3</span></div><div class="layui-card-body">';
}

function returnOpenOption(data) {
  return '<div class="layui-input-block">' +
    '<textarea name="answer3" readonly="readonly" class="layui-textarea"' +
    ' title="" lay-verify="required" autocomplete="off">' + data + '</textarea>' +
    '</div></div></div>';
}

function delQuestion(elem) {
  let layuiCard = $('.layui-card'),
    index = elem.parents('.layui-card').index();
  for (let i = index + 1; i < layuiCard.length; i++) {
    layuiCard.eq(i).find('.question-no').text(i);
  }
  layuiCard.eq(index).remove();
}

$('input[name=singleScale], input[name=multiScale], input[name=openScale]').keyup(function () {
  let reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
  if (reg.test(this.value)) {
    this.value = '';
  } else {
    if (!this.value.match(/^[+\-]?\d*?\.?\d*?$/))
      this.value = this.value.substring(0, this.value.length - 1);
  }
});

$('input[name=restrict]').keyup(function () {
  let reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
  if (reg.test(this.value)) {
    this.value = '';
  } else {
    if (!this.value.match(/^\d*?$/))
      this.value = this.value.substring(0, this.value.length - 1);
  }
});